#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient
import sys

SERVER = '10.188.188.101'
PORT = 27017
DB_NAME = "pmc2"
COLLECTION_NAME = "mesh"
connection = MongoClient(SERVER, PORT)
db = connection[DB_NAME]
collection = db[COLLECTION_NAME]

infile = open(sys.argv[1], "r")
for line in infile:
    line = line.rstrip()
    splitline = line.split(",")
    pmid = int(splitline[1])
    descriptor = splitline[2][1:-1].split(".")[0]
    result = collection.find({"pmid": pmid}).count()
    if result == 0:
        collection.insert_one({"pmid": pmid, "descriptor": [descriptor]})
    elif result == 1:
        collection.update_one({"pmid": pmid}, {"$addToSet": {"descriptor": descriptor}})
    else:
        print str(pmid) + "\t" + descriptor
infile.close()
connection.close()
